package com.lalosoft.gastostarjetaweb.dao;

import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.lalosoft.gastostarjetaweb.model.GmailAccount;
import com.lalosoft.gastostarjetaweb.pmf.PMF;
import com.lalosoft.gastostarjetaweb.util.AESEncrypt;

public class GmailAccountDao {
	
	private static final Logger log = Logger.getLogger("GmailAccountDao");
	
	public static GmailAccount getAccount(String token){
		GmailAccount account = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(GmailAccount.class);
		List<GmailAccount> list = (List<GmailAccount>)q.execute();
		boolean encontrado = false;
		int pos = 0;
		while(!encontrado && pos < list.size() ){
			GmailAccount temp = list.get(pos);
			if(temp.getToken().equals(token)){
				encontrado = true;
				account = temp;
				log.log(Level.WARNING, "Cuenta encontrada");
			}
			pos++;
		}
		return account;
	}
	
	public static String saveAccount(String user, String pass) throws Exception {
		String uuid = UUID.randomUUID().toString();
		GmailAccount account = new GmailAccount();
		account.setUsername(user);
		account.setToken(uuid);
		AESEncrypt aesEncrypt = new AESEncrypt();
		String key = aesEncrypt.getKey();
		account.setAesKey(key);
		String passEncriptado = aesEncrypt.encripta(pass);
		account.setPassword(passEncriptado);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(account);
			log.log(Level.WARNING, "Nueva Key guardada");
		} finally {
			pm.close();
		}
		return uuid;
	}

}
